#!/usr/bin/env python
# coding=utf-8
import os
import shutil
import math
from tkinter import messagebox
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog, Entry, Button, StringVar
import cv2
import numpy as np

def create_window(parent=None):
    global offX, offY
    offX = 60
    offY = 50

    # 裁剪图片边界区域
    global left_value, right_value, up_value, down_value,center_x,center_y,canvas_width,canvas_height,root_after2
    left_value = 1
    right_value = 1
    up_value = 1
    down_value = 1
    center_x = 0
    center_y = 0
    canvas_width = 750
    canvas_height = 800
    center_x = canvas_width / 2
    center_y = canvas_height / 2
    root_after2=None
    global imgs_scale,imgs_Dic,dirName_Dic,scale_value, scale_index,cur_directory_type_index,scale_img
    cur_directory_type_index = 0
    scale_value = 1
    imgs_Dic = {}
    dirName_Dic={}
    imgs_scale = []
    scale_index = 0
    scale_img=1
    # 创建窗口
    if parent is None:
        root = tk.Tk()
    else:
        root = tk.Toplevel(parent)
    root.title("txt切割")
    root.config(bg="grey")
    root.geometry("1000x1000+0+0")

    # 图像绘制位置坐标
    canvas = tk.Canvas(root, width=800, height=800, bg="gray")
    canvas.place(x=offX + 70, y=offY + 100)

    mainFile = u'生成'

    def select_directory(entry_var):
        """弹出选择目录对话框"""
        directory = filedialog.askdirectory(parent=root)
        entry_var.set(directory)
        root.lift()

    # 获取输入路径
    def get_input_path():
        global image_frames, last_button, next_button, image_frames_path, image_frames_path1, image_frames_output_path, image_frames_output_path1
        global all_directory_type, cur_directory_type_index
        # 路径一
        all_directory_type = []
        cur_directory_type_index = 0
        image_frames_path = entry_scale_frame_path.get().replace("\\", "/")
        if image_frames_path != '':
            image_frames_output_path = image_frames_path + "_output"
            all_directory = [d for d in os.listdir(image_frames_path) if
                             os.path.isdir(os.path.join(image_frames_path, d))]
            dir_name = ""
            for i, d in enumerate(all_directory):
                net_dir_name = os.path.basename(d)
                if dir_name.split("_")[0] == net_dir_name.split("_")[0]:
                    all_directory_type[-1].append(net_dir_name)
                else:
                    dir_name = net_dir_name
                    all_directory_type.append([dir_name])

        if not all_directory_type:
            messagebox.showerror("Error", "路径一没有目录")
            # return
    # 第一行：按钮+输入框
    entry_scale_frame_path = StringVar()
    entry_path = Entry(root, textvariable=entry_scale_frame_path)
    entry_path.place(x=offX + 350, y=offY -27)
    button1 = Button(root, text="输入目录", command=lambda: select_directory(entry_scale_frame_path),
                           bg='skyblue')
    button1.place(x=offX + 500, y=offY -30)

    check_var = tk.IntVar()
    tk.Label(root, text="勾选显示十字线", bg='green').place(x=offX + 750, y=offY -27)
    tk.Checkbutton(root, variable=check_var).place(x=offX + 850, y=offY - 30)

    check_var1 = tk.IntVar()
    tk.Label(root, text="勾选加载当前目录", bg='green').place(x=offX + 600, y=offY - 27)
    tk.Checkbutton(root, variable=check_var1).place(x=offX + 700, y=offY - 30)

    # 第二行：输入框
    tk.Label(root, text="请输入高度", bg='green').place(x=offX + 350, y=offY+5)
    entry_scale_width = StringVar()
    entry_path1 = Entry(root, textvariable=entry_scale_width)
    entry_path1.place(x=offX + 420, y=offY+5)

    # 第三行：输入框
    tk.Label(root, text="请输入宽度", bg='green').place(x=offX + 350, y=offY + 35)
    entry_scale_height = StringVar()
    entry_path1 = Entry(root, textvariable=entry_scale_height)
    entry_path1.place(x=offX + 420, y=offY + 35)

    # 第三行：x,y偏差
    tk.Label(root, text="请输入X偏移量", bg='green').place(x=offX + 550, y=offY + 5)
    entry_scale_X =StringVar(value="0")
    entry_path1 = Entry(root, textvariable=entry_scale_X)
    entry_path1.place(x=offX + 620, y=offY + 5)

    tk.Label(root, text="请输入Y偏移量", bg='green').place(x=offX + 550, y=offY + 35)
    entry_scale_Y = StringVar(value="0")
    entry_path1 = Entry(root, textvariable=entry_scale_Y)
    entry_path1.place(x=offX + 620, y=offY + 35)

    # 第四行：按钮
    button1 = Button(root, text="预览", command=lambda: load_images(),
                     bg='skyblue')
    button1.place(x=offX + 350, y=offY + 65)

    button1 = Button(root, text="原图缩放倍数", command=lambda: Scale_img(),
                     bg='skyblue')
    button1.place(x=offX + 720, y=offY + 65)
    entry_scale = StringVar()
    entry_path1 = Entry(root, textvariable=entry_scale,width=5)
    entry_path1.place(x=offX + 670, y=offY + 65)

    def check_status():
        if check_var.get():
            return 'on'
        else:
            return 'off'

    def check_status1():
        if check_var1.get():
            return 'on'
        else:
            return 'off'

    def Scale_img():
        global scale_img
        scale_img=float(entry_scale.get())

    def btn_last_directory():
        global cur_directory_type_index,scale_index
        if cur_directory_type_index <= 0:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index -= 1
        scale_index = 0

    def btn_next_directory():
        global cur_directory_type_index,scale_index
        if cur_directory_type_index >= len(imgs_Dic) - 1:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index += 1
        scale_index=0
    def CreateDir(path):
        isExists = os.path.exists(path)

        # 判断结果
        if not isExists:
            # 如果不存在则创建目录
            # 创建目录操作函数
            os.makedirs(path)

            print(path + u'创建成功')
            return True
        else:
            # 如果目录存在则不创建，并提示目录已存在
            # print(path+u'目录已存在')
            return False
    def transparent_back(img):
        img = img.convert('RGBA')
        L, H = img.size
        # if L == 1 or H == 1:
        # return False

        return img

    def PlayReSizeImage(input_image_path, scale_factor):
        # 尝试读取图像
        image = cv2.imread(input_image_path, cv2.IMREAD_UNCHANGED)  # 保留透明度通道
        if image is None:
            print(f"无法读取图像：{input_image_path}")

        # 判断图像是否有Alpha通道
        if image.shape[2] == 4:  # 图像是RGBA格式，包含透明度通道
            bgr_image = image[:, :, :3]  # 只取BGR部分（不包括Alpha通道）
            alpha_channel = image[:, :, 3]  # 获取Alpha通道
        else:
            bgr_image = image
            alpha_channel = None

        # 将图像从 BGR 格式转换为 RGB 格式（因为 OpenCV 使用 BGR，而 PIL 使用 RGB）
        rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)

        # 使用 OpenCV 的 INTER_CUBIC 插值方法进行放大
        enlarged_image = cv2.resize(rgb_image, (0, 0), fx=scale_factor, fy=scale_factor, interpolation=cv2.INTER_CUBIC)

        if alpha_channel is not None:
            # 对于带有透明度的图像，放大Alpha通道
            enlarged_alpha = cv2.resize(alpha_channel, (0, 0), fx=scale_factor, fy=scale_factor,
                                        interpolation=cv2.INTER_CUBIC)
            # 合并RGB和Alpha通道
            enlarged_image = np.dstack((enlarged_image, enlarged_alpha))

        # 使用 PIL 进一步处理图像
        pil_image = Image.fromarray(enlarged_image)
        return pil_image

    def combine_photo():
        inputPath = entry_scale_frame_path.get()

        imageW = int(entry_scale_width.get())

        imageH = int(entry_scale_height.get())
        off_x = int(entry_scale_X.get())
        off_y = int(entry_scale_Y.get())
        path = ''

        for x in inputPath:
            path += x
            if x == '\\':
                path += '\\'

        path = os.path.normpath(path)
        CreateDir(os.path.join(path, mainFile))
        # CreateDir(path+'\\'+mainFile)

        # print(os.listdir(path))
        for dirName in os.listdir(path):
            dealDir = path + '\\' + dirName
            if os.path.isdir(dealDir) and dirName != mainFile:
                index = 1
                max_x = []
                max_y = []
                for pngName in os.listdir(dealDir):
                    if os.path.isfile(dealDir + '\\' + pngName):
                        bg = Image.open(dealDir + '\\' + pngName)
                        bg1 = transparent_back(bg)
                        W,H=bg1.size
                        max_x.append(W)
                        max_y.append(H)
                for pngName in os.listdir(dealDir):
                    if os.path.isfile(dealDir + '\\' + pngName):
                        img1 = Image.open(dealDir + '\\' + pngName)
                        img2 = transparent_back(img1)
                        print(img2)
                        str = pngName[0:-4]
                        saveFile = path + '\\' + mainFile + '\\' + dirName
                        if img2 != False:
                            size_x = int(max(max_x) * 1.5)
                            size_y = int(max(max_y) * 1.5)
                            toImage = Image.new('RGBA', (imageW,imageH), (255, 255, 255, 0))

                            print(u'处理图片', dealDir + '\\' + pngName)

                            pos = []
                            txtName = dealDir + '\\Placements\\' + str + '.txt'
                            print(u'打开目标txt', txtName)
                            fp = open(txtName, 'r')
                            done = False
                            while not done:
                                aline = fp.readline()
                                if aline != '' and aline != ' ':
                                    if int(aline):
                                        pos.append(int(aline))
                                    else:
                                        pos.append(0)
                                else:
                                    done = True
                            fp.close()
                            if len(pos) == 0:
                                pos = [0, 0]
                            r, g, b, a = img2.split()
                            # toImage.paste(img2, (int(236 / 2) + pos[0] - 24+off_x, int(216 / 2) + pos[1] - 18+off_y))
                            # toImage.paste(img2, (int(imageW / 2) + pos[0] * (-1 ** index) - 24,
                            # int(imageH / 2) + pos[1] * (-1 ** index) - 18))
                            paste_x = imageW / 2 + pos[0]*scale_img - 24 + off_x
                            paste_y = imageH / 2 + pos[1]*scale_img - 18 + off_y

                            toImage.paste(img2,
                                          (int(paste_x), int(paste_y)))
                            index+=1
                            CreateDir(saveFile)
                            toImage.save(saveFile + '\\' + str + '.png')
                            if toImage is not None:
                                toImage.close()
                                print(u'图片关闭')
                        else:
                            print(u'复制文件'),
                            shutil.copy(dealDir + '\\' + pngName, saveFile + '\\' + str + '.png')
    def combine_cur_photo():
        inputPath = entry_scale_frame_path.get()

        imageW = int(entry_scale_width.get())

        imageH = int(entry_scale_height.get())

        off_x = int(entry_scale_X.get())
        off_y = int(entry_scale_Y.get())
        path = ''

        for x in inputPath:
            path += x
            if x == '\\':
                path += '\\'

        path = os.path.normpath(path)
        CreateDir(os.path.join(path, mainFile))
        isdirName=False
        dirName=None
        if check_status1() == 'on':
            dealDir = path
            isdirName=True
        else:
            dirName = dirName_Dic[cur_directory_type_index]
            dealDir = path + '\\' + dirName
            isdirName=dirName != mainFile

        if os.path.isdir(dealDir) and isdirName:
            for pngName in os.listdir(dealDir):
                if os.path.isfile(dealDir + '\\' + pngName):
                    img1 = Image.open(dealDir + '\\' + pngName)
                    img2 = transparent_back(img1)
                    print(img2)
                    str = pngName[0:-4]
                    if dirName is None:
                        saveFile = path + '\\' + mainFile
                    else:
                        saveFile = path + '\\' + mainFile + '\\' + dirName
                    if img2 != False:
                        toImage = Image.new('RGBA', (imageW, imageH), (255, 255, 255, 0))

                        print(u'处理图片', dealDir + '\\' + pngName)

                        pos = []
                        txtName = dealDir + '\\Placements\\' + str + '.txt'
                        print(u'打开目标txt', txtName)
                        fp = open(txtName, 'r')
                        done = False
                        while not done:
                            aline = fp.readline()
                            if aline != '' and aline != ' ':
                                if int(aline):
                                    pos.append(int(aline))
                                else:
                                    pos.append(0)
                            else:
                                done = True
                        fp.close()
                        if len(pos) == 0:
                            pos = [0, 0]
                        #r, g, b, a = img2.split()
                        #toImage.paste(img2, (int(imageW / 2) + pos[0] - 24, int(imageH / 2) + pos[1] - 18))

                        paste_x = imageW / 2 + pos[0]*scale_img - 24 + off_x
                        paste_y = imageH / 2 + pos[1]*scale_img - 18 + off_y

                        toImage.paste(img2,
                                      (int(paste_x), int(paste_y)))

                        CreateDir(saveFile)
                        toImage.save(saveFile + '\\' + str + '.png')
                        if toImage is not None:
                            toImage.close()
                            print(u'图片关闭')

                    else:
                        print(u'复制文件'),
                        shutil.copy(dealDir + '\\' + pngName, saveFile + '\\' + str + '.png')

    last_button = tk.Button(root, text="上一个", command=btn_last_directory)
    last_button.place(x=offX + 405, y=offY + 65)

    next_button = tk.Button(root, text="下一个", command=btn_next_directory)
    next_button.place(x=offX + 465, y=offY + 65)

    button2 = tk.Button(root, text="导出当前", command=combine_cur_photo)
    button2.place(x=offX + 525, y=offY + 65)

    button2 = tk.Button(root, text="导出全部", command=combine_photo)
    button2.place(x=offX + 595, y=offY + 65)

    # 刷新帧率图片
    def update_frame_sclae():
        global imgs_scale, scale_index, photo, resized_img, name, root_after2

        if cur_directory_type_index in dirName_Dic:
            canvas.delete("all")
            length = len(imgs_Dic[dirName_Dic[cur_directory_type_index]])
            img_scale = imgs_Dic[dirName_Dic[cur_directory_type_index]][scale_index]
            resize = [math.ceil(img_scale.size[0] * scale_value), math.ceil(img_scale.size[1] * scale_value)]
            resized_img = img_scale.resize(resize, Image.Resampling.LANCZOS)
            photo = ImageTk.PhotoImage(resized_img)
            x = int(photo.width() / 2)
            y = int(photo.height() / 2)

            canvas.create_rectangle(center_x - photo.width() / 2, center_y - photo.height() / 2, center_x + photo.width() / 2,
                                    center_y + photo.height() / 2, fill="white", outline="black")
            canvas.create_image(center_x, center_y, anchor=tk.CENTER, image=photo)

            if check_status() == 'on':
                canvas.create_line(0, center_y, canvas_width, center_y, fill="red", width=1)
                canvas.create_line(center_x, 0, center_x, canvas_height, fill="red", width=1)

            scale_index = (scale_index + 1) % length  # 循环显示
        root_after2 = root.after(200, update_frame_sclae)
    def load_images():
        global scale_index, cur_directory_type_index
        scale_index=0
        cur_directory_type_index=0
        inputPath = entry_scale_frame_path.get()

        path = ''

        for x in inputPath:
            path += x
            if x == '\\':
                path += '\\'

        path = os.path.normpath(path)

        dirName_Dic.clear()
        imgs_Dic.clear()
        i=0
        if check_status1() == 'on':
            for dirName in os.listdir(path):
                dirName_Dic[i] = dirName
            loadresource(path, 0)
        else:
            for dirName in os.listdir(path):
                dealDir = path + '\\' + dirName
                dirName_Dic[i] = dirName
                if os.path.isdir(dealDir) and dirName != mainFile:
                    loadresource(dealDir,i)
                i += 1
        print(imgs_Dic)
        if root_after2:
            root.after_cancel(root_after2)
        update_frame_sclae()
    image_extensions = ['.png', '.jpg', '.jpeg', '.bmp', '.gif']
    def loadresource(path,curIndex):

        imageW = int(entry_scale_width.get())

        imageH = int(entry_scale_height.get())

        off_x = int(entry_scale_X.get())
        off_y = int(entry_scale_Y.get())

        cur_img = []
        cur_img.clear()
        max_x = []
        max_y = []
        i = 0
        for dirName in os.listdir(path):
            dealDir = path + '\\' + dirName
            i += 1
            # 获取文件扩展名
            _, ext = os.path.splitext(dealDir)
            if ext.lower() in image_extensions:
                bg = Image.open(dealDir)
                bg1 = transparent_back(bg)
                W, H = bg1.size
                max_x.append(W)
                max_y.append(H)
        index = 0
        for pngName in os.listdir(path):
            dealDir = path + '\\' + pngName
            # 获取文件扩展名
            _, ext = os.path.splitext(dealDir)
            if ext.lower() in image_extensions:
                img1 = Image.open(dealDir)
                img2 = transparent_back(img1)
                print(img2)
                str = pngName[0:-4]
                if img2 != False:
                    size_x = int(max(max_x) * 1.5)
                    size_y = int(max(max_y) * 1.5)
                    toImage = Image.new('RGBA', (imageW, imageH), (255, 255, 255, 0))
                    print(u'处理图片', dealDir + '\\' + pngName)

                    pos = []
                    txtName = path + '\\Placements\\' + str + '.txt'
                    print(u'打开目标txt', txtName)
                    fp = open(txtName, 'r')
                    done = False
                    while not done:
                        aline = fp.readline()
                        if aline != '' and aline != ' ':
                            if int(aline):
                                pos.append(int(aline))
                            else:
                                pos.append(0)
                        else:
                            done = True
                    fp.close()
                    if len(pos) == 0:
                        pos = [0, 0]
                    r, g, b, a = img2.split()
                    # toImage.paste(img2, (int(236 / 2) + pos[0] - 24+off_x, int(216 / 2) + pos[1] - 18+off_y))
                    # toImage.paste(img2, (int(imageW / 2) + pos[0] * (-1 ** index) - 24,
                    # int(imageH / 2) + pos[1] * (-1 ** index) - 18))
                    paste_x = imageW / 2 + pos[0] * scale_img - 24 * scale_value + off_x
                    paste_y = imageH / 2 + pos[1] * scale_img - 18 * scale_value + off_y

                    # toImage.paste(img2,
                    #               (math.ceil(paste_x), math.ceil(paste_y)))
                    paste_x_int = round(paste_x)
                    paste_y_int = round(paste_y)
                    toImage.paste(img2,
                                  (paste_x_int, paste_y_int))
                    index += 1
                    cur_img.append(toImage)
        imgs_Dic[dirName_Dic[curIndex]]=cur_img

    #重置窗口
    def reset_window(width,height):
        global image_max_width, image_max_height, canvas_width, canvas_height, center_x, center_y
        image_max_width = width
        image_max_height = height
        canvas_width = 1000
        canvas_height = 1000
        center_x = 0
        center_y = 0
        root_width = max(canvas_width, image_max_width)
        root_height = max(canvas_height, image_max_height)
        # 处理大图
        root.geometry(f"{root_width}x{root_height}+{0}+{0}")
        canvans_width = max(800, image_max_width)
        canvans_height = max(800, image_max_height)
        canvas.config(width=canvans_width, height=canvans_height)
        center_x = canvans_width / 2
        center_y = canvans_height / 2
    if parent is None:
        root.mainloop()

    # mainFile = u'生成'
    # def select_directory():
    #     root = tk.Tk()
    #     root.withdraw()  # 隐藏主窗口
    #
    #     # 打开文件选择对话框并选择目录
    #     directory_path = filedialog.askdirectory(title="请选择一个目录")
    #
    #     if directory_path:
    #         print("选择的目录路径:", directory_path)
    #     else:
    #         print("未选择任何目录")
    #     return directory_path
if __name__ == "__main__":
    create_window()